<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <!-- <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <!-- 操作按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['repairLine:repairLine:add']"
        >新增</el-button>
      </el-col>
      <!-- 其他按钮不变 -->
    </el-row>

    <!-- 维修单行列表 -->
    <el-table v-loading="loading" :data="repairLineList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="行ID" align="center" prop="lineId" />
      <el-table-column label="维修单ID" align="center" prop="repairId" />
      <el-table-column label="项目ID" align="center" prop="subjectId" />
      <el-table-column label="项目编码" align="center" prop="subjectCode" />
      <el-table-column label="项目名称" align="center" prop="subjectName" />
      <el-table-column label="项目类型" align="center" prop="subjectType" />
      <el-table-column label="项目内容" align="center" prop="subjectContent" />
      <el-table-column label="标准" align="center" prop="subjectStandard" />
      <el-table-column label="故障描述" align="center" prop="malfunction" />
      <el-table-column label="故障描述资源" align="center" prop="malfunctionUrl" />
      <el-table-column label="维修情况" align="center" prop="repairDes" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['repairLine:repairLine:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['repairLine:repairLine:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备维修单行对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="repairLineRef" :model="form" :rules="rules" label-width="80px">
        <!-- 维修单ID自动填充且禁止编辑 -->
        <el-form-item label="维修单ID" prop="repairId">
          <el-input 
            v-model="form.repairId" 
            placeholder="请输入维修单ID" 
            disabled
          />
        </el-form-item>
        
        <!-- 选择项目名称（优化为统一表单样式） -->
        <el-form-item label="选择项目名称" prop="subjectId" :required="true">
          <el-cascader
            v-model="cascaderValue"
            :options="subjectOptions"
            :props="cascaderProps"
            @change="handleSubjectChange"
            placeholder="请选择项目类型和项目名称"
          />
        </el-form-item>
        
        <!-- 项目编码（只读，由项目选择自动填充） -->
        <el-form-item label="项目编码" prop="subjectCode">
          <el-input 
            v-model="form.subjectCode" 
            placeholder="请输入项目编码" 
            disabled
          />
        </el-form-item>
        
        <!-- 项目类型（只读，由项目选择自动填充） -->
        <el-form-item label="项目类型" prop="subjectType">
          <el-input 
            v-model="form.subjectType" 
            placeholder="请输入项目类型" 
            disabled
          />
        </el-form-item>
        
        <!-- 项目内容（只读，由项目选择自动填充） -->
        <el-form-item label="项目内容">
          <editor 
            v-model="form.subjectContent" 
            :min-height="192"
            disabled
          />
        </el-form-item>
        
        <el-form-item label="标准" prop="subjectStandard">
          <el-input v-model="form.subjectStandard" placeholder="请输入标准" />
        </el-form-item>
        
        <el-form-item label="故障描述" prop="malfunction">
          <el-input v-model="form.malfunction" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        
        <el-form-item label="故障描述资源" prop="malfunctionUrl">
          <el-input v-model="form.malfunctionUrl" placeholder="请输入故障描述资源" />
        </el-form-item>
        
        <el-form-item label="维修情况" prop="repairDes">
          <el-input v-model="form.repairDes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RepairLine">
import { listRepairLine, getRepairLine, delRepairLine, addRepairLine, updateRepairLine } from "@/api/repairLine/repairLine"
// 导入项目API
import { listSubject } from "@/api/subject/subject"
import { ref, reactive, getCurrentInstance, watch, onMounted } from 'vue'

const { proxy } = getCurrentInstance()

// 子组件数据定义
const repairLineList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 项目相关变量
const subjectOptions = ref([]) // 分类后的项目选项
const cascaderValue = ref([]) // 级联选择器的值
const subjectLoading = ref(false) // 项目加载状态

// 核心数据
const data = reactive({
  form: {
    lineId: null,
    repairId: null,
    subjectId: null,
    subjectCode: null,
    subjectName: null,
    subjectType: null,
    subjectContent: null,
    subjectStandard: null,
    malfunction: null,
    malfunctionUrl: null,
    repairDes: null,
    remark: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    repairId: null
  },
  rules: {
    repairId: [
      { required: true, message: "维修单ID不能为空", trigger: "blur" }
    ],
    malfunction: [
      { required: true, message: "故障描述不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 级联选择器配置
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: false
}

// 接收主组件传递的repairId
const props = defineProps({
  currentRepairId: {
    type: [Number, String, null],
    default: null
  }
});

// 获取项目列表并按类型分类
const getSubjectList = () => {
  subjectLoading.value = true
  listSubject({}).then(response => {
    // 按subject_type分类
    const typeMap = {}
    
    // 先收集所有类型
    response.rows.forEach(item => {
      if (!typeMap[item.subjectType]) {
        typeMap[item.subjectType] = []
      }
      typeMap[item.subjectType].push({
        id: item.subjectId,
        name: item.subjectName,
        ...item
      })
    })
    
    // 转换为级联选择器需要的格式
    subjectOptions.value = Object.keys(typeMap).map(type => ({
      id: type,
      name: type, // 类型名称作为一级选项
      children: typeMap[type]
    }))
    
    subjectLoading.value = false
  }).catch(error => {
    console.error("获取项目列表失败：", error)
    subjectLoading.value = false
  })
}

// 处理项目选择变化
const handleSubjectChange = (value) => {
  if (!value || value.length < 2) return
  
  // value格式: [类型, 项目ID]
  const subjectId = value[1]
  
  // 查找选中的项目
  let selectedSubject = null
  subjectOptions.value.forEach(typeItem => {
    const found = typeItem.children.find(item => item.id === subjectId)
    if (found) {
      selectedSubject = found
    }
  })
  
  // 自动填充表单（项目编码、类型、内容等只读字段）
  if (selectedSubject) {
    form.value.subjectId = selectedSubject.id
    form.value.subjectName = selectedSubject.name
    form.value.subjectCode = selectedSubject.subjectCode
    form.value.subjectType = selectedSubject.subjectType
    form.value.subjectContent = selectedSubject.subjectContent
    form.value.subjectStandard = selectedSubject.subjectStandard || ''
  }
}

const isMounted = ref(false);

// 组件挂载时
onMounted(() => {
  isMounted.value = true;
  // 获取项目列表
  getSubjectList()
  
  // 挂载后若有currentRepairId，直接查询
  if (props.currentRepairId) {
    queryParams.value.repairId = props.currentRepairId;
    getList();
  }
});

// 监听repairId变化
watch(
  () => props.currentRepairId,
  (newVal) => {
    if (isMounted.value) {
      queryParams.value.repairId = newVal;
      if (newVal) {
        getList();
      } else {
        repairLineList.value = [];
        total.value = 0;
      }
    }
  },
  { immediate: false }
);

/** 查询设备维修单行列表 */
function getList() {
  if (!queryParams.value.repairId) {
    repairLineList.value = [];
    total.value = 0;
    loading.value = false;
    return;
  }
  loading.value = true;
  listRepairLine(queryParams.value).then(response => {
    repairLineList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    console.error("查询接口失败：", error);
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    lineId: null,
    repairId: props.currentRepairId || null,
    subjectId: null,
    subjectCode: null,
    subjectName: null,
    subjectType: null,
    subjectContent: null,
    subjectStandard: null,
    malfunction: null,
    malfunctionUrl: null,
    repairDes: null,
    remark: null,
  };
  cascaderValue.value = [];
  proxy.resetForm("repairLineRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.repairId = props.currentRepairId;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.lineId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.repairId = props.currentRepairId;
  open.value = true;
  title.value = "添加设备维修单行";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _lineId = row.lineId || ids.value;
  getRepairLine(_lineId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备维修单行";
    
    // 设置级联选择器的值，显示已选中的项目
    if (form.value.subjectId && form.value.subjectType) {
      cascaderValue.value = [form.value.subjectType, form.value.subjectId];
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["repairLineRef"].validate(valid => {
    if (valid) {
      if (form.value.lineId != null) {
        updateRepairLine(form.value).then(response => {  
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRepairLine(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _lineIds = row.lineId || ids.value;
  proxy.$modal.confirm(`确定要删除选中的${_lineIds.length > 1 ? '维修单行' : '维修单行'}吗？`).then(() => {
    return delRepairLine(_lineIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('repairLine/repairLine/export', {
    ...queryParams.value
  }, `repairLine_${new Date().getTime()}.xlsx`);
}

// 初始加载时如果有repairId则查询
if (props.currentRepairId) {
  getList();
}
</script>